#!/usr/bin/env python
# This is a simple plugin for Munin http://munin.projects.linpro.no/
# to graph page load times for various HTTP requests.

import sys

MAX_LABEL_WIDTH = 25
SERVER_ROOT = 'http://browsershots.org/'

if sys.argv[0].endswith('_screenshots'):
    TITLE = "Screenshots page load times"
    PAGES = [('screenshots', '/screenshots/'),
             ('screenshot', '/screenshots/4243e1d1b24b2cf66840c035c957cb2a/')]
elif sys.argv[0].endswith('_factories'):
    TITLE = "Factories page load times"
    PAGES = [('factories', '/factories/'),
             ('factory', '/factories/slog/')]
elif sys.argv[0].endswith('_websites'):
    TITLE = "Websites page load times"
    PAGES = [('websites', '/websites/'),
             ('website', '/http://browsershots.org/')]
elif sys.argv[0].endswith('_requests'):
    TITLE = "Requests page load times"
    PAGES = [('requests', '/requests/'),
             ('request', '/requests/437061/')]
else:
    TITLE = "Page load times"
    PAGES = [('home', '/'),
             ('browsers', '/browsers/add/'),
             ('priority', '/priority/'),
             ('error404', '/404/')]


if len(sys.argv) == 2 and sys.argv[1] == 'config':
    print """
graph_title %(TITLE)s
graph_vlabel seconds
graph_args --base 1000 -l 0
graph_scale no
graph_category performance
graph_info The page load times for various HTTP requests.
""".strip() % locals()
    for name, path in PAGES:
        url = SERVER_ROOT.rstrip('/') + path
        if len(path) > MAX_LABEL_WIDTH:
            path = path[:MAX_LABEL_WIDTH - 3] + '...'
        print "%s.label %s" % (name, path)
        print "%s.info %s" % (name, url)
        print "%s.warning 3" % name
        print "%s.critical 10" % name
else:
    import time
    import urllib2
    for name, path in PAGES:
        url = SERVER_ROOT.rstrip('/') + path
        start = time.time()
        try:
            html = urllib2.urlopen(url).readlines()
            if 'debug' in sys.argv:
                while html and html[0].strip() == '':
                    html = html[1:]
                sys.stderr.write(html[0])
                while html and html[-1].strip() == '':
                    html = html[:-1]
                sys.stderr.write(html[-1])
        except:
            pass
        elapsed = time.time() - start
        print "%s.value %.3f" % (name, elapsed)
